package com.itbaizhan.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.itbaizhan.dao.LoginLogDao;
import com.itbaizhan.dao.RedisDao;
import com.itbaizhan.exception.BusException;
import com.itbaizhan.pojo.LoginLog;
import com.itbaizhan.result.BaseResult;
import com.itbaizhan.result.CodeEnum;
import com.itbaizhan.service.LoginServcie;
import com.itbaizhan.utils.RandomUtil;
import io.netty.util.internal.StringUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author spf
 * @date 2024/3/6
 * @time 14:32
 */
@Service
public class LoginServiceImpl implements LoginServcie {

    @Value("${message.accessKeyId}")
    private String accessKeyId;
    @Value("${message.accessKeySecret}")
    private String accessKeySecret;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private LoginLogDao loginLogDao;

    @Override
    public void sendYZM(String phone) {
        // 查询原来验证码是否还有效
        String code = redisDao.get(phone);
        if (StringUtil.isNullOrEmpty(code)) {
            // 生成验证码
            String checkCode = RandomUtil.buildCheckCode(4);
            redisDao.set(phone, checkCode);
            System.out.println("手机号：" + phone + ",验证码：" + checkCode);
        } else {
            throw new BusException(CodeEnum.SENDED_CODE_ERROR);
        }
    }

    @Override
    public String login(String phone, String code) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(phone);
        loginLog.setType("1");
        loginLog.setLoginTime(new Date());

        String value = redisDao.get(phone);
        if (StringUtil.isNullOrEmpty(value)){
            loginLog.setSuccess(false);
            loginLog.setMessage("验证码已过期");
            loginLogDao.insertLog(loginLog);
            throw new BusException(CodeEnum.EXPIRED_CODE_ERROR);
        }
        if (!code.equals(value)){
            loginLog.setSuccess(false);
            loginLog.setMessage("验证码不匹配");
            loginLogDao.insertLog(loginLog);
            throw new BusException(CodeEnum.CODE_ERROR);
        }
        loginLog.setSuccess(true);
        loginLog.setMessage("登陆成功！");
        loginLogDao.insertLog(loginLog);
        redisDao.delete(phone);
        return phone;
    }

    @SneakyThrows
    @Override
    public BaseResult sendMessage(String phone, String code) {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        Client client = createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\""+ code +"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
        if ("OK".equals(response.getBody().getCode())) {
            return new BaseResult(200, response.getBody().getMessage(), null);
        } else {
            return new BaseResult(500, response.getBody().getMessage(), null);
        }
    }

    @SneakyThrows
    public Client createClient(String accessKeyId, String accessKeySecret) {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }


}
